odoo.define('lmch_buliao.worker', function (require) {
    var Model = require('web.Model');
    var SaleOrder = new Model('sale.order');
    // 存储全局信息
    odoo.buliao_info = {
        "cur_wait_so_offset": 0, // 待生产SO偏移
        "cur_done_weight_offset": 0, // 已完成weight偏移
        "cur_so_id": false, // 当前生产的订单编号
        "cur_so_name": false, // 当前生产的订单名称
        "cur_qty": 0, // 当前生产的是第几匹
        "buliao_qty": 0, // 订单的总匹数
        "cur_modify_weight_id": false // 正在修改的weight
    };

    // 改变生产界面信息
    var change_ui_info = function(change_info){
        // 面板
        $("#so_name").text(change_info.so_name);
        $("#partner_name").text(change_info.partner_name);
        $("#buliao_qty").text(change_info.buliao_qty);
        $("#cur_qty").text(change_info.cur_qty);
        // 按钮
        if(odoo.buliao_info.cur_so_id){
            $("#start_produce").addClass("hidden");
            $("#stop_produce").removeClass("hidden");
            $("#input_so").attr("readonly", true);
            $("#input_weight").attr("readonly", false);
            $("#submit_weight").removeClass("disabled");
            $("#input_weight").focus()
        }else{
            $("#start_produce").removeClass("hidden");
            $("#stop_produce").addClass("hidden");
            $("#input_so").attr("readonly", false);
            $("#input_so").val("");
            $("#input_weight").attr("readonly", true);
            $("#input_weight").val("");
            $("#submit_weight").addClass("disabled");

        }
    }

    // 改变修改界面信息
    var change_modify_ui_info = function(info){
        // info 为空时对界面进行重置
        var so_name = "";
        var weight = "";
        if(info){
            so_name = info.so_name;
            weight = info.weight;
            $("#submit_new_weight").removeClass("disabled");
            $("#modify_weight_clear").removeClass("disabled");
            $("#new_weight").attr("readonly", false);
            $("#new_weight").focus();
        }else{
            $("#submit_new_weight").addClass("disabled");
            $("#modify_weight_clear").addClass("disabled");
            $("#new_weight").val("");
            $("#new_weight").attr("readonly", true);
        }
        $("#modify_so_name").val(so_name);
        $("#origin_weight").val(weight)
    }

    var print_tag = function(res){
        //定义数据脚本
        var _reportData = {
          "Template": "buliao_tag_heng.fr3",
          "Printer": "Gprinter GP-3100TU",
          "Tables": [
            {
              "Name": "Table1",
              "Cols": [
                {"type": "str", "size": 25, "Name": "partner", "required": false},
                {"type": "str", "size": 25, "Name": "buliao_type", "required": false},
                {"type": "str", "size": 25, "Name": "customer_origin", "required": false},
                {"type": "Float", "size": 12, "Name": "buliao_width", "required": false},
                {"type": "Float", "size": 12, "Name": "buliao_g_weight", "required": false},
                {"type": "Float", "size": 12, "Name": "weight", "required": false},
                {"type": "str", "size": 25, "Name": "number", "required": false},
                {"type": "str", "size": 25, "Name": "done_date", "required": false}
              ],
              "Data": [res]
            }
          ]
        };
        _reportData.Tables.Data;
        sendMsg(_reportData);
    }

    var start_produce = function(res){
        var change_info = {
            "so_name":  "SO编号："+res.name,
            "partner_name": "客户："+res.partner_name,
            "buliao_qty": "总匹数："+res.buliao_qty,
            "cur_qty": "当前匹数："+res.cur_qty,
        }
        // 更改全局信息
        odoo.buliao_info.cur_so_id = res.id;
        odoo.buliao_info.cur_so_name = res.name;
        odoo.buliao_info.buliao_qty = res.buliao_qty;
        odoo.buliao_info.cur_qty = res.cur_qty;
        change_ui_info(change_info);
        // 刷新表格，移除正在生产的so
        refresh_wait_table();
    }

    var stop_produce = function(){
        var change_info = {
            "so_name":  "SO编号：空",
            "partner_name": "客户：空",
            "buliao_qty": "总匹数：0",
            "cur_qty": "当前匹数：0",
        }
        // 更改全局信息
        odoo.buliao_info.cur_so_id = false;
        odoo.buliao_info.cur_so_name = false;
        odoo.buliao_info.cur_qty = 0;
        odoo.buliao_info.buliao_qty = 0;
        change_ui_info(change_info);
        // 刷新表格,如果so部分完成则将so添加到任务表格
        refresh_wait_table();
    }

    var btn_modify_weight_clear = function(){
        odoo.buliao_info.cur_modify_weight_id = false;
        change_modify_ui_info(false);
        refresh_done_table();
    }

    var submit_weight = function(weight){
        SaleOrder.call("generate_buliao_weight", [[odoo.buliao_info.cur_so_id], weight, odoo.buliao_info.cur_qty])
                 .then(function(res){
                    odoo.buliao_info.cur_qty += 1;
                    if(odoo.buliao_info.cur_qty > odoo.buliao_info.buliao_qty){
                        stop_produce();
                    }else{
                        $("#cur_qty").text("当前匹数："+odoo.buliao_info.cur_qty);
                        $("#input_weight").val("");
                    }
                    refresh_done_table();
                    print_tag(res);
                 })
    }

    var btn_submit_weight = function(){
            var weight = $("#input_weight").val();
            weight = parseFloat(weight);
            if(!weight){
                alert("输入的匹重有误，请检查后重新输入！");
                return
            }
            submit_weight(weight);
    }

    var btn_submit_new_weight = function(){
            console.log('111');
            var new_weight = $("#new_weight").val();
            new_weight = parseFloat(new_weight);
            if(!new_weight){
                alert("输入的匹重有误，请检查后重新输入！");
                return
            }
            SaleOrder.call("modify_weight", [new_weight, odoo.buliao_info.cur_modify_weight_id])
                     .then(function(res){
                        btn_modify_weight_clear();
                        print_tag(res);
                     })
    }

    // 表格生产按钮
    var table_start_produce = function(){
        if(odoo.buliao_info.cur_so_id){
            alert("订单 ["+odoo.buliao_info.cur_so_name+"] 正在生产，请先停止！");
            return
        }
        var so_id = this.id.slice(6);
        so_id = parseInt(so_id);
        SaleOrder.call("get_so_qty", [[so_id]])
                 .then(function(res){
                    if(res.warning){
                        alert(res.warning);
                    }else{
                        // 从表格添加的任务需要在输入框填入SO编号
                        $("#input_so").val(res.name);
                        start_produce(res);
                    }
                 });
    }

    // 表格修改
    var table_modify = function(){
        var weight_id = this.id.slice(15);
        weight_id = parseInt(weight_id);
        SaleOrder.call("get_modify_weight_info", [weight_id])
                 .then(function(res){
                    if(res.warning){
                        alert(res.warning);
                    }else{
                        odoo.buliao_info.cur_modify_weight_id = res.id;
                        change_modify_ui_info(res);
                        refresh_done_table();

                    }
                 })
    }

    var generate_wait_table_tr = function(s){
        var so_id = s[0];
        // 不添加正在生产的订单
        if(so_id===odoo.buliao_info.cur_so_id){
            return
        }
        var html = "<tr>";
        for(var x=1; x<s.length; x++){
            html += "<td>"+s[x]+"</td>"
        }
        var btn_id = "so_id_"+so_id;
        html += "<td><button id='"+btn_id+"'>生产</button></td>"
        html += "</tr>";
        $("#wait_so_table").append(html);
        $("#"+btn_id).click(table_start_produce);
    }

    var generate_done_table_tr = function(s){
        var weight_id = s[0];
        var html = "<tr>";
        for(var x=1; x<s.length; x++){
            html += "<td>"+s[x]+"</td>"
        }
        var btn_id = "done_weight_id_"+weight_id;
        html += "<td><button id='"+btn_id+"'>修改</button></td>"
        html += "</tr>";
        $("#done_weight_table").append(html);
        $("#"+btn_id).click(table_modify);
    }

    var refresh_table = function(info){
        SaleOrder.call(info.method, info.args)
         .then(function(so){
            // var len = Math.min(so.length, 5) 在服务器使用limit限制
            $(info.table_id).empty();
            // so.slice(0, len).forEach(generate_wait_table_tr);
            so.forEach(info.tr_generate_method);
         });
    }

    var refresh_wait_table = function(){
        var info = {
            "method": "get_wait_so",
            "args": [odoo.buliao_info.cur_wait_so_offset, odoo.buliao_info.cur_so_id],
            "table_id": "#wait_so_table",
            "tr_generate_method": generate_wait_table_tr
        };
        refresh_table(info);
    }

    var refresh_done_table = function(){
        var info = {
            "method": "get_done_weights",
            "args": [odoo.buliao_info.cur_done_weight_offset, odoo.buliao_info.cur_modify_weight_id],
            "table_id": "#done_weight_table",
            "tr_generate_method": generate_done_table_tr
        };
        refresh_table(info);
    }

    var switch_page = function(info){
        SaleOrder.call(info.method, info.args)
                 .then(function(so){
                    if(so.length > 0){
                        var offset = info.offset;
                        $(info.table_id).empty();
                        so.forEach(info.tr_generate_method);
                        // 下一页
                        if(info.is_next){
                            if(offset === 0){
                                // 第一次点击下一页，改变上一页为可点击状态
                                $(info.previous_li_id).removeClass("disabled");
                            }
                            offset += 5;
                        }else{
                            offset -= 5;
                            if(offset === 0){
                                // 偏移变为0时改变上一页为不可点击
                                $(info.previous_li_id).addClass("disabled");
                            }
                        }
                        switch(info.method){
                            case "get_wait_so":
                                odoo.buliao_info.cur_wait_so_offset = offset;
                                break;
                            case "get_done_weights":
                                odoo.buliao_info.cur_done_weight_offset = offset;
                                break;
                        }
                    }else{
                        alert("已经没有数据了！");
                    }
                 })
    }

    $(function () {
        // 开始生产
        $("#start_produce").click(function(){
            if(odoo.buliao_info.cur_so_id){
                alert("订单 ["+odoo.buliao_info.cur_so_name+"] 正在生产，请先停止！");
                return
            }
            var so_name = $("#input_so").val()
            SaleOrder.call("get_so_qty_byname", [so_name])
                     .then(function(res){
                        if(res.warning){
                            alert(res.warning);
                        }else{
                            start_produce(res);
                        }
                     })
        });

        // 停止生产
        $("#stop_produce").click(function(){
            stop_produce();
        })
        // 提交匹重
        $("#submit_weight").click(btn_submit_weight);

        // 提交匹重修改
        $("#submit_new_weight").click(btn_submit_new_weight);

        // 清除修改信息
        $("#modify_weight_clear").click(btn_modify_weight_clear);

        $("#wait_so_next_page").click(function(){
            var info = {
                "method": "get_wait_so",
                "args": [odoo.buliao_info.cur_wait_so_offset+5, odoo.buliao_info.cur_so_id],
                "is_next": true,
                "table_id": "#wait_so_table",
                "previous_li_id": "#wait_so_previous_li",
                "tr_generate_method": generate_wait_table_tr,
                "offset": odoo.buliao_info.cur_wait_so_offset
            }
            switch_page(info);
        })

        $("#wait_so_previous_page").click(function(){
            if(odoo.buliao_info.cur_wait_so_offset === 0){
                alert("没有数据了！");
                return
            }
            var info = {
                "method": "get_wait_so",
                "args": [odoo.buliao_info.cur_wait_so_offset-5, odoo.buliao_info.cur_so_id],
                "is_next": false,
                "table_id": "#wait_so_table",
                "previous_li_id": "#wait_so_previous_li",
                "tr_generate_method": generate_wait_table_tr,
                "offset": odoo.buliao_info.cur_wait_so_offset
            }
            switch_page(info);
        })

        $("#done_weight_next_page").click(function(){
            var info = {
                "method": "get_done_weights",
                "args": [odoo.buliao_info.cur_done_weight_offset+5, odoo.buliao_info.cur_modify_weight_id],
                "is_next": true,
                "table_id": "#done_weight_table",
                "previous_li_id": "#done_weight_previous_li",
                "tr_generate_method": generate_done_table_tr,
                "offset": odoo.buliao_info.cur_done_weight_offset
            }
            switch_page(info);
        })

        $("#done_weight_previous_page").click(function(){
            if(odoo.buliao_info.cur_done_weight_offset === 0){
                alert("没有数据了！");
                return
            }
            var info = {
                "method": "get_done_weights",
                "args": [odoo.buliao_info.cur_done_weight_offset-5, odoo.buliao_info.cur_modify_weight_id],
                "is_next": false,
                "table_id": "#done_weight_table",
                "previous_li_id": "#done_weight_previous_li",
                "tr_generate_method": generate_done_table_tr,
                "offset": odoo.buliao_info.cur_done_weight_offset
            }
            switch_page(info);
        })

        $("#input_weight").keypress(function(e){
            if(e.which == 13){
                btn_submit_weight();
            }
        });

        $("#new_weight").keypress(function(e){
            if(e.which == 13){
                btn_submit_new_weight();
            }
        })

        refresh_wait_table();
        refresh_done_table();
    });

    // 每隔5秒刷新一次待生产表格
    window.setInterval(refresh_wait_table, 30000);
    window.setInterval(refresh_done_table, 30000);
});